package com.bungarus.busi;

import com.bungarus.model.BungarusClientException;
import com.bungarus.model.MessageBuilder;
import com.bungarus.utils.IPAddressUtils;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 *
 * Created by tang on 2018/11/17.
 */
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(ClientHeartbeatHandler.class);

    private final InnerClient client;

    public ClientHeartbeatHandler(InnerClient client) {
        this.client = client;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            ctx.writeAndFlush(MessageBuilder.buildHeartbeatPingMessage(client.connectionFromWhichCluster))
                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
        else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress socketAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        IPAddressUtils.HostPortPair hostPortPair = new IPAddressUtils.HostPortPair();
        hostPortPair.host = socketAddress.getHostString();
        hostPortPair.port = socketAddress.getPort();
        this.client.unregisterInnerClientConnectionMap(hostPortPair);

        try {
            this.client.connectNextNode(ctx.channel().eventLoop());
        }
        catch (BungarusClientException e){
            this.client.reLoadRemoteServers(ctx.channel().eventLoop());
        }
        super.channelInactive(ctx);
    }
}
